package com.iscas.lndicatormonitor.controller;

import com.iscas.lndicatormonitor.common.CustomResult;
import com.iscas.lndicatormonitor.domain.Plan;
import com.iscas.lndicatormonitor.domain.Record;
import com.iscas.lndicatormonitor.dto.*;
import com.iscas.lndicatormonitor.service.PlanService;
import com.iscas.lndicatormonitor.service.RecordService;
import com.iscas.lndicatormonitor.service.UsersService;
import com.iscas.lndicatormonitor.service.WorkflowService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/plan")
public class PlanController {
    @Autowired
    PlanService planService;
    @Autowired
    WorkflowService workflowService;

    @Autowired
    RecordService recordService;

    @Autowired
    UsersService usersService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/insertPlan")
    public CustomResult insertPlan(@RequestBody AddPlanDTO addPlanDTO) throws Exception {
        int workflowId = workflowService.workflowInsert(addPlanDTO.getWorkflowDTO());
        PlanDTO planDTO = addPlanDTO.getPlanDTO();
        planDTO.setWorkflowId(workflowId);
        Boolean result =  planService.planInsert(planDTO,addPlanDTO.getFaultConfigIdList());
        if (result){
            // 关联
            return CustomResult.ok();
        }else {
            return new CustomResult(40000,"插入失败",null);
        }
    }
    @GetMapping("/getAllPlan")
    public CustomResult getAllPlan() throws Exception {
        List<Plan> planList = planService.getAllPlan();
        List<PlanListItemDTO> planListItemDTOList = new ArrayList<>();

        for (Plan plan : planList) {
            PlanListItemDTO dto = new PlanListItemDTO();

            // 先取基本字段
            dto.setId(plan.getId());
            dto.setName(plan.getName());
            dto.setCreateTime(plan.getCreateTime());
            dto.setUpdateTime(plan.getUpdateTime());

            // 设置创建者名称
            dto.setCreator(usersService.getRealNameById(plan.getCreatorId()));

            // 计算注入故障总数
            String nodesString = workflowService.getWorkflowById(plan.getWorkflowId()).getNodes();
            if (nodesString != null && !nodesString.isEmpty()) {
                dto.setFaultNum(nodesString.split(",").length);
            } else {
                dto.setFaultNum(0);
            }
            // 计算状态
            List<Record> records = recordService.getRecordsByPlanId(plan.getId());
            Record latestRecord = null;

            for (Record record : records) {
                if (record.getEndTime() == null) {
                    latestRecord = record;
                    break;  // 当发现endTime为null的记录时，立即终止循环
                } else if (latestRecord == null || record.getEndTime().after(latestRecord.getEndTime())) {
                    latestRecord = record;
                }
            }
            if (latestRecord != null) {
                dto.setStatus(latestRecord.getRecordStatus() == null ? 0 : latestRecord.getRecordStatus());
            } else {
                dto.setStatus(0); // 未开始
            }
            planListItemDTOList.add(dto);
        }
        return CustomResult.ok(planListItemDTOList);
    }

    // 获取单个计划信息 包括计划的基本信息(包括流程图、压测文件等) 还有执行记录信息
    @GetMapping("/getPlanById")
    public CustomResult getPlanById(int planId) throws Exception {
        // 获取单个计划信息
        Plan plan = planService.getPlanById(planId);
        PlanSpecDTO planSpecDTO = new PlanSpecDTO();
        BeanUtils.copyProperties(plan,planSpecDTO);
        planSpecDTO.setCreator(usersService.getRealNameById(plan.getCreatorId()));
        SinglePlanDTO singlePlanDTO = new SinglePlanDTO();
        singlePlanDTO.setPlanSpecDTO(planSpecDTO);
        // 获取此计划下的所有记录信息
        List<Record> recordList = recordService.getRecordsByPlanId(plan.getId());
        List<RecordItemDTO> recordItemDTOList = new ArrayList<>();
        for (Record record: recordList){
            RecordItemDTO recordItemDTO = new RecordItemDTO();
            BeanUtils.copyProperties(record,recordItemDTO);
            recordItemDTO.setPlayer(usersService.getRealNameById(record.getPlayerId()));
            recordItemDTOList.add(recordItemDTO);
        }
        singlePlanDTO.setRecordList(recordItemDTOList);
        return CustomResult.ok(singlePlanDTO);
    }

    // 更新计划信息
    @PostMapping("/updatePlan")
    public CustomResult updatePlan(@RequestBody AddPlanDTO updatePlanDTO) throws Exception {
        WorkflowDTO workflowDTO = updatePlanDTO.getWorkflowDTO();
        workflowDTO.setId(updatePlanDTO.getPlanDTO().getWorkflowId());
        if (planService.planUpdate(updatePlanDTO.getPlanDTO()) && workflowService.workflowUpdate(workflowDTO)){
            return CustomResult.ok();
        }else {
            return new CustomResult(40000,"更新失败",null);
        }
    }
}
